import { getChanlvConfigApi, createLinkerApi, deleteLinkerApi, getScanCertificateApi, getPassengerTypeConfApi } from '../../api/index'
import { buildForm, setEditForm, compareForm } from '../../utils/changlv'
import { asyncToast, getBirthAndSex, setEvent, setPage } from '../../utils/index'
import { channel } from '../../utils/constants'
import { STORAGE_KEY } from '../../utils/storage'
import dayjs from 'dayjs'
import { ticketTypeBuilder, checkBeiHaiTicket } from '../booking/main'
import {
  SHIP_CERT_TYPE,
  SHIP_PASSENGER_SEX,
  SHIP_PASSENGER_TYPE,
  SHIP_PASSENGER_TYPE_BEIHAI,
  TRACER_PAGES,
  PRODUCT_CODE
} from '../../utils/constants'

const SHIP_EDIT_FORM = {
  nationType: 0,
  nationality: '',
  firstCertType: 0,
  firstCertNo: '',
  secondCertType: 0,
  secondCertNo: '',
  nationalityDetail: '',
  linkerName: '',
  englishXin: '',
  englishMing: '',
  passportDate: '',
  issueDate: '',
  issueNum: '',
  sex: 0,
  birthday: '',
  visaDate: '',
  visaNum: '',
  StayDays: 0,
  VisaType: '',
  listNos: [],
  linkerType: 0
}

const pageName = TRACER_PAGES['create']

Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    formItems: [],
    isFormValid: false,
    errMsg: [],

    addedPassengers: [],

    shipCertType: SHIP_CERT_TYPE,
    shipPassengerType: SHIP_PASSENGER_TYPE,
    shipPassengerSex: SHIP_PASSENGER_SEX,
    settings: {},

    editForm: SHIP_EDIT_FORM,

    currentIsIdCard: false,
    isOpenVerifyFail: false,

    // 证件识别相关
    formTemp: {},

    isOpenCertExam: false,
    certExamObj: {
      title: '温馨提示',
      img: ''
    },


    showTicketPicker: false,
    passengerTypeConf: {},
    pickerPassenger: {},

    isGoon: false,
    ticketTypePickerPassengers: {},
    validDialog: {
      show: false,
      list: [],
      success: () => { }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      query: options
    })
    wx.setNavigationBarTitle({
      title: `${options.editId ? '编辑' : '新增'}常旅`
    })
    this.init(options)
  },

  onShow: function () {
    setPage(pageName, PRODUCT_CODE)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('ship_edit_passenger')
  },


  init: function (query) {
    const that = this
    const { lineId, supplierId, editId, category } = query
    that.getChanglvConfig({
      LineId: lineId,
      SupplierId: supplierId
    })



  },


  getChanglvConfig: function (startLine) {
    const that = this
    const { LineId, SupplierId } = startLine
    const { editId } = this.data.query
    let editForm = that.data.editForm
    if (!LineId) return
    wx.showLoading({
      title: '正在加载...',
      mask: true,
      success: (result) => {

      },
      fail: () => { },
      complete: () => { }
    });
    getChanlvConfigApi({ LineId }).then(response => {
      let formItems = []
      let editPassenger = editForm
      if (editId) {
        editPassenger = wx.getStorageSync('ship_edit_passenger') || editForm || {};
      }
      editPassenger = that.setDefaultCertNo(response, editPassenger)

      const _editPassenger = setEditForm(editPassenger, response, true, editPassenger)
      formItems = buildForm(false, response, SupplierId, _editPassenger)

      const isFormValid = this._validForm(formItems)

      const currentIsIdCard = this.checkCertIncludeCardId(formItems)

      // 请求票型配置
      that.getPassengerTypeConf(startLine)

      that.setData({
        formItems,
        settings: response,
        isFormValid,
        editForm: _editPassenger,
        currentIsIdCard
      })

      wx.hideLoading();
    })
  },


  // 表单 item change事件
  bindPickerChange: function(e) {
    const data = e.currentTarget.dataset.ranges
    const id = e.currentTarget.dataset.id
    const settings = this.data.settings
    const { category, supplierId } = this.data.query
    let editForm = this.data.editForm
    const setNations = Object.keys(settings)
    const certKeys = Object.keys(SHIP_CERT_TYPE)
    const certValues = Object.values(SHIP_CERT_TYPE)
    const sexKeys = Object.keys(SHIP_PASSENGER_SEX)
    const sexValues = Object.values(SHIP_PASSENGER_SEX)
    const value = e.detail.value
    var opt = editForm

    let typing = true, restNo = false
    switch (id) {
      case 1:
        typing = false
        // 切换国籍 重置证件类型
        // changlvShip.init();
        opt.nationType = setNations[e.detail.value]
        break;
      case 2:
        break;
      case 3:
        opt.linkerName = value
        break;
      case 4:
        opt.englishXin = value
        break;
      case 5:
        opt.englishMing = value
        break;
      case 6:
        restNo = true
        opt.firstCertType = certKeys[certValues.indexOf(data[value])]
        break;
      case 7:
        opt.firstCertNo = value
        break;
      case 8:
        opt.sex = value
        break;
      case 9:
        opt.birthday = value
        break;
      case 10:
        opt.passportDate = value
        break;
      case 11:
        opt.issueDate = value
        break;
      case 12:
        opt.issueNum = value
        break;
      case 13:
        restNo = true
        opt.secondCertType = certKeys[certValues.indexOf(data[value])]
        break;
      case 14:
        opt.secondCertNo = value
        break;
      case 15:
        opt.visaDate = value
        break;
      case 20:
        opt.visaNum = value
        break;
      case 21:
        opt.stayDays = value
        break;
      case 22:
        opt.visaType = SHIP_VISA_TYPE[value]
        break;

    }

    if (opt.sex && sexValues.includes(opt.sex)) {
      opt.sex = sexKeys[sexValues.indexOf(opt.sex)]
    }

    // // 表单 赋值
    setEditForm(opt, settings, typing, restNo, opt)

    // // 构建表单 item
    const formItems = buildForm(category, settings, supplierId, opt)

    const currentIsIdCard = this.checkCertIncludeCardId(formItems)

    this.setData({
      editForm: opt,
      formItems,
      currentIsIdCard
    })

    this.setData({
      isFormValid: this._validForm(formItems)
    })
  
  },

  // 表单校验
  _validForm: function(items) {
    let errMsg = []
    items.map(item => {
      if (item.required) {
        if (typeof item.selectorValue === 'string' && !item.selectorValue.trim()) {
          item.msg = `请输入${item.title}`
          errMsg.push(item)
        }
      }
    })

    this.setData({
      errMsg
    })

    return errMsg.length === 0
  },


  // 获取当前证件类型是否包含身份证
  checkCertIncludeCardId: function (formItems) {
    let currentCert = false
    const certFormItems = formItems.filter(item => item.id === 6 || item.id === 13)
    if (certFormItems.length > 0) {
      const certTypeItems = certFormItems.map(item => Number(item.selectorValue))
      currentCert = certTypeItems.includes(1)
    }

    return currentCert
  },



  setDefaultCertNo: function (linkerSetting, editPassenger) {
    const { passenger, invalidMsg } = compareForm(editPassenger, linkerSetting, true)
    if (passenger.validFirstCert && passenger.validFirstCert.certNo) {
      passenger.listNos.forEach(item => {
        if (item.certType === 2) {
          passenger.passportDate = ''
          if (dayjs(item.certActiveTime).isAfter(dayjs())) {
            passenger.passportDate = item.certActiveTime
          }
        }
      })

      // isDefault 为 1 的默认展示
      passenger.firstCertType = passenger.validFirstCert.certType
      passenger.firstCertNo = passenger.validFirstCert.certNo
      if (passenger.validSecondCert && passenger.validSecondCert.certNo) {
        const filterSecondEditP = passenger.validSecondCert
        passenger.secondCertType = filterSecondEditP.certType
        passenger.secondCertNo = filterSecondEditP.certNo
      }
    }

    if (passenger.listNos) {
      passenger.listNos.forEach(item => {
        item.certActiveTime = dayjs(item.certActiveTime).isAfter(dayjs()) ? item.certActiveTime : ''
      })
    }

    return passenger
  },


  onPageClick: function (e) {
    const that = this
    const url = e.currentTarget.dataset.url
    let editForm = this.data.editForm
    const settings = this.data.settings
    const { lineId, supplierId, editId, category } = this.data.query
    wx.navigateTo({
      url,
      events: {
        selectNationChannel: function ({ data }) {
          const {
            nationalityDetail,
            nationalityThreeCode,
            nationalityTwoCode
          } = data

          editForm.nationalityDetail = nationalityDetail
          editForm.nationalityThreeCode = nationalityThreeCode
          editForm.nationalityTwoCode = nationalityTwoCode

          const formItems = buildForm(category, settings, supplierId, editForm)
          that.setData({
            editForm,
            formItems
          })
        }
      }
    });
  },

  createLinker: function (_form) {
    const that = this
    const { editId, category } = this.data.query
    const formItems = this.data.formItems
    const editForm = this.data.editForm
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    let errMsg = []

    formItems.map(item => {
      let _selectVal = item.selectorValue
      if (typeof item.selectorValue === 'string') {
        _selectVal = item.selectorValue.trim()
      }
      if (item.required) {
        if (!_selectVal) {
          item.msg = `请输入${item.title}`
          errMsg.push(item)
        }
        if (item.reg && !item.reg.test(_selectVal)) {
          item.msg = `请输入正确格式${item.title}`
          if (item.id === 7 || item.id === 14) {
            item.msg = `请输入正确格式${item.title}`
          }
          errMsg.push(item)
        }
      }
      if (item.name) {
        _form[item.name] = item.selectorValue
      }

      if (item.name === "nationalityDetail") {
        _form.nationalityThreeCode = editForm.nationalityThreeCode
        _form.nationalityTwoCode = editForm.nationalityTwoCode
      }
    })
    console.log("errMsg: ", errMsg)

    if (errMsg && errMsg.length > 0) {
      wx.showToast({
        title: errMsg[0].msg,
        icon: 'none',
        duration: 2000
      })

      return;
    }

    let certList = []
    // let firstCertIndex = __values(SHIP_CERT_TYPE).indexOf(_form.firstCertType)
    // let _firstCertType = __keys(SHIP_CERT_TYPE)[firstCertIndex]

    let _certActiveTime = ''

    // 设置护照有效期
    if (Number(_form.firstCertType) === 2) {
      _certActiveTime = _form.passportDate
    }

    certList.push({
      certType: Number(_form.firstCertType),
      certNo: _form.firstCertNo || '',
      certActiveTime: _certActiveTime,
      certId: 0,
      isDefault: 1
    })
    if (_form.secondCertType) {
      // let secondCertIndex = __values(SHIP_CERT_TYPE).indexOf(_form.secondCertType)
      // let _secondCertType = __keys(SHIP_CERT_TYPE)[secondCertIndex]
      certList.push({
        certType: Number(_form.secondCertType),
        certNo: _form.secondCertNo || '',
        certActiveTime: _certActiveTime,
        certId: 0,
        isDefault: 0
      })
    }
    // FIXME: 整合memberId的获取
    let formData = {
      channel: channel,
      // openId: "=oOCyauESm73l_-wE2SJWBQFY01Ns",
      // unionId: "ohmdTt5nZemOu5rr6dmQgJS-VXzI",
      openId,
      unionId,
      memberId,
      shipMemberId: 0,
      shipLinkerId: 0,
      linkerName: _form.linkerName || '',
      mobile: "",
      phone: "",
      sex: _form.sex === '女' ? 0 : 1,
      email: "",
      englishXin: _form.englishXin || '',
      englishMing: _form.englishMing || '',
      birthday: _form.birthday || '',
      isDefault: 1,
      overSeasMobilephone: "",
      listNos: certList,
      linkerType: _form.linkerType || 0,
      visaDate: _form.visaDate || '',
      issueNum: _form.issueNum || 0,
      issueDate: _form.issueDate && dayjs(_form.issueDate).format('YYYY-MM-DD') || '',
      nationality: _form.nationality || '',
      nationalCode: "",
      nationalityDetail: _form.nationalityDetail || '',
      nationalityThreeCode: _form.nationalityThreeCode || '',
      nationalityTwoCode: _form.nationalityTwoCode || '',

      visaNum: _form.visaNum || '',
      stayDays: _form.stayDays || 0,
      visaType: _form.visaType || '',
    }
    if (editId) {
      formData.id = editId
    }

    // if(goon) {
    //     setVts('订单填写页', 'DD30', '')
    // } else {
    //     setVts('订单填写页', 'DD31', `${editId? '编辑': '新增'}`)
    // }

    // 证件重复校验
    const repeatCerts = this.checkCertRepeat(_form.firstCertNo, _form.secondCertNo, category)
    if (repeatCerts && repeatCerts.length > 0) {
      wx.showToast({
        title: repeatCerts[0],
        icon: 'none',
        duration: 2000
      })
      return;
    }

    wx.showLoading({
      title: '正在加载...',
      mask: true,
      success: (result) => {

      },
      fail: () => { },
      complete: () => { }
    });

    // wx.removeStorageSync(STORAGE_KEY.selectedIds)
    return createLinkerApi(formData).then(response => {

      if (!response || response.status !== 200) {
        return
      }
      if (!response.data || response.data.Code !== 10000) {
        asyncToast({
          title: '操作失败，请稍后再试',
          icon: 'none',
          duration: 1000
        })
        return
      }
      asyncToast({
        title: editId ? '编辑成功' : '新增成功',
        icon: 'success',
        duration: 1000
      })


      const createId = response.data.Data
      let selectedIds = wx.getStorageSync(STORAGE_KEY.selectedIds)
      if (createId) {
        selectedIds += `|${createId}-${formData.linkerType}`
      }
      wx.setStorageSync(STORAGE_KEY.selectedIds, selectedIds)
      wx.setStorageSync(STORAGE_KEY.afterCreate, 1)
      return response

    })
  },

  createCallBack: function (isGoon, passenger) {
    const that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('createPassengerChannel', { data: passenger });
    that.resetForm();
    wx.hideLoading();
    if (!isGoon) {
      wx.navigateBack()
    }
  },

  resetForm: function () {
    const settings = this.data.settings
    const { supplierId } = this.data.query
    const editForm = {
      nationType: 0,
      nationality: '',
      firstCertType: 0,
      firstCertNo: '',
      secondCertType: 0,
      secondCertNo: '',
      nationalityDetail: '',
      linkerName: '',
      englishXin: '',
      englishMing: '',
      passportDate: '',
      issueDate: '',
      issueNum: '',
      sex: 0,
      birthday: '',
      visaDate: '',
      visaNum: '',
      StayDays: 0,
      VisaType: '',
      listNos: []
    }
    editForm.linkerType = 0

    const { passenger, invalidMsg } = compareForm(editForm, settings, false)
    const formItems = buildForm(false, settings, supplierId, passenger)

    wx.removeStorageSync('ship_edit_passenger')
    this.setData({
      editForm,
      formItems,
      isFormValid: false
    })
  },

  // 校验证件重复
  checkCertRepeat: function (first, second, category) {
    const { passengers } = this.data;
    const { editId } = this.data.query;
    const _linkers = Object.assign([], passengers);
    let repeatCerts = []
    if (!_linkers || _linkers.length <= 0) return;
    if (category) {
      const _filterStudents = _linkers.filter(item => item.linkerType === 2 && item.id !== editId);
      _filterStudents.map(student => {
        student.listNos.map(cert => {
          if ((first && first === cert.certNo) || (second && second === cert.certNo)) {
            repeatCerts.push(`当前证件与【${student.linkerName}】的证件【${SHIP_CERT_TYPE[cert.certType]}】重复`)
          }
        })
      })
      return repeatCerts;
    }
    _linkers.map(item => {
      if (item.linkerType !== 2 && (!editId || item.id !== editId)) {
        item.listNos.map(cert => {
          if ((first && first === cert.certNo) || (second && second === cert.certNo)) {
            repeatCerts.push(`当前证件与【${item.linkerName}】的证件【${SHIP_CERT_TYPE[cert.certType]}】重复`)
          }

        })
      }
    })
    return repeatCerts;

  },


  // 提交新增编辑常旅表单
  onConfirm: function(e) {
    const that = this
    let editForm = this.data.editForm
    const type = e.currentTarget.dataset.type
    const formItems = this.data.formItems
    const isFormValid = this._validForm(formItems)
    const errMsg = this.data.errMsg
    const isGoon = type === 'keep'

    if(isGoon) {
      setEvent('订单填写页', 'DD30', '')
    } else {
      setEvent('订单填写页', 'DD31', `^${editForm.id? '更新': '新增'}^`)
    }

    if(type === 'back') {
      wx.navigateBack({
        delta: 1
      });
      setEvent('订单填写页', 'DD47', '')
      return
    }
    if (!isFormValid && errMsg.length > 0) {
      wx.showToast({
        title: errMsg[0].msg,
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (Number(editForm.firstCertType) === 1 && editForm.firstCertNo) {
      const certInfo = getBirthAndSex(editForm.firstCertNo)
      editForm.birthday = certInfo.birthDay
      editForm.sex = certInfo.sex
    }

    let fullName = []
    if (editForm.linkerName) {
      fullName.push(editForm.linkerName)
    }
    if (editForm.englishMing && editForm.englishXin) {
      fullName.push(editForm.englishXin + '-' + editForm.englishMing)
    }

    if (fullName.length > 0) {
      editForm.showName = fullName.join('/')
    }
    let validList = []
    if (editForm.showName) validList.push({
      'key': '姓名',
      'value': editForm.showName
    })
    if (editForm.firstCertType) validList.push({
      'key': SHIP_CERT_TYPE[editForm.firstCertType],
      'value': editForm.firstCertNo
    })
    if (editForm.secondCertType) validList.push({
      'key': SHIP_CERT_TYPE[editForm.secondCertType],
      'value': editForm.secondCertNo
    })
    let _errMsg = []
    formItems.map(item => {
      let _selectVal = item.selectorValue
      if (typeof item.selectorValue === 'string') {
        _selectVal = item.selectorValue.trim()
      }
      if (item.required) {
        if (!_selectVal) {
          item.msg = `请输入${item.title}`
          _errMsg.push(item)
        }
        if (item.reg && !item.reg.test(_selectVal)) {
          item.msg = `请输入正确格式${item.title}`
          if (item.id === 7 || item.id === 14) {
            item.msg = `请输入正确格式${item.title}`
          }
          _errMsg.push(item)
        }
      }
    })
    console.log("errMsg: ", _errMsg)

    if (_errMsg && _errMsg.length > 0) {
      wx.showToast({
        title: _errMsg[0].msg,
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      validDialog: {
        show: true,
        list: validList,
        success: function (e) {
          return that.sendData(editForm, isGoon)
        }
      }
    })
    return
  },
  sendData(editForm, createPromise, isGoon) {
    const that = this
    let addedPassengers = that.data.addedPassengers
    const settings = that.data.settings
    const {
      limit,
      seatPrice,
      childSeatPrice,
      displayName,
      oldSeatPrice,
      citizenChildSeatPrice,
      citizenSeatPrice,
      ticketLeft,
      supportChild,
      supportOld,
    } = that.data.query
    const passengerTypeConf = that.data.passengerTypeConf
    const seat = {
      ChildSeatPrice: childSeatPrice,
      DisplayName: displayName,
      OldSeatPrice: oldSeatPrice,
      SeatPrice: seatPrice,
      CitizenChildSeatPrice: citizenChildSeatPrice,
      CitizenSeatPrice: citizenSeatPrice,
      ticketLeft
    }
    const { ticketTypePickerPassengers, ticketTypeChoose, passenger } = ticketTypeBuilder({
      passengerTypeConf,
      seat,
      p: editForm,
      supportChild: supportChild === '1',
      supportOld: supportOld === '1'
    })
    that.setData({
      isGoon,
      ticketTypePickerPassengers
    })

    return new Promise((resolve, reject) => {

      if (ticketTypeChoose) {
        that.ticketPickerDialogOpen(passenger)
        resolve()
        return;
      }

      if (isGoon) { 
        const createPromise = that.createLinker(editForm)
        createPromise && createPromise.then(response => {
          // addedPassengers
          const { passenger, invalidMsg } = compareForm(editForm, settings)
          addedPassengers.push(passenger)
          that.setData({
            addedPassengers
          })

          resolve()
          that.createCallBack(isGoon, editForm)
        })
        return
      } 
      const createLinkerPromise = that.createLinker(editForm)
      createLinkerPromise && createLinkerPromise.then(response => {
        resolve()
        that.createCallBack(isGoon, editForm)
      })
    })
  },


  // 选择票型
  onChooseTicketType: function(e) {
    const item = e.detail
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)

    ticketTypePickerPassengers.list.forEach(_item => {
      _item.isSelected = false
      if (item.id === _item.id) {
        _item.isSelected = true
      }
    })
    this.setData({
      ticketTypePickerPassengers
    })

    if(ticketTypePickerPassengers.passenger) {
      const _type = ticketTypePickerPassengers.passenger.linkerType
  
      setEvent('订单填写页', 'DD36', `^票型选择:${SHIP_PASSENGER_TYPE_ORDER[_type]}^`)

    }
  },

  // 票种弹框确认事件
  onConfirmTciketType: function(e) {
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)
    const selectedTicketType = ticketTypePickerPassengers.list.filter(item => item.isSelected)[0]

    setEvent('订单填写页', 'DD37', '')

    if(!selectedTicketType) {
      return
    }
    const passengers = this.data.passengers

    const { passenger } = ticketTypePickerPassengers

    const {
      citizenChildSeatPrice,
      citizenSeatPrice,
      lineId,
      supplierId,
      voyageCabinId,
    } = this.data.query


    // 北海市民 校验
    const isBeiHai = [0, 1, 22, 24].includes(selectedTicketType.type) && (citizenSeatPrice > 0 || citizenChildSeatPrice > 0)
    if (isBeiHai) {

      checkBeiHaiTicket({
        BelongType: SHIP_PASSENGER_TYPE_BEIHAI[selectedTicketType.type], // (1:岛民,2:市民,3:员工票,4:市民儿童,5:普通成人,6:普通儿童)
        SupplierId: supplierId,
        CertNo: passenger.firstCertNo,
        PassengerName: passenger.linkerName,
        CarryChildCertNo: passenger.carryChildCert || '',
        VoyageCabinId: voyageCabinId || 1,
        LineId: lineId,
      }, passenger.linkerType).then(response => {
        if (response) {
          this.changeTicketType(passengers, passenger, selectedTicketType)
        }
      })

      return
    }

    this.changeTicketType(passengers, passenger, selectedTicketType)
  },


  changeTicketType: function (passengers, createP, selectedTicketType) {
    const that = this
    const isGoon = that.data.isGoon
    let addedPassengers = this.data.addedPassengers
    const settings = this.data.settings

    createP.linkerType = selectedTicketType.type
    if (isGoon) {
      const createPromise = that.createLinker(createP)
      createPromise && createPromise.then(response => {
        const { passenger, invalidMsg} = compareForm(createP, settings)
        addedPassengers.push(passenger)
        that.setData({
          addedPassengers
        })

        that.createCallBack(isGoon, createP)
        that.closeTicketTypeLayout()
      })
      return
    }

    that.closeTicketTypeLayout()

    const createLinkerPromise = that.createLinker(createP)
    createLinkerPromise && createLinkerPromise.then(response => {
      that.createCallBack(isGoon, createP)


    })
  },

  closeTicketTypeLayout() {
    this.setData({
      showTicketPicker: false,
    })
  },

  getPassengerTypeConf: function ({ LineId }) {
    const that = this
    return getPassengerTypeConfApi({ LineId }).then(response => {
      that.setData({
        passengerTypeConf: response
      })
      return response
    })
  },


  // 票型选择弹框 打开
  ticketPickerDialogOpen(p) {
    this.setData({
      showTicketPicker: true,
      pickerPassenger: p
    })
  },

  onDelete: function (e) {
    const that = this
    const id = e.currentTarget.dataset.id
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    deleteLinkerApi({
      TCLinkerId: id,
      ShipLinkerId: 0,
      ShipMemberId: '',
      TCMemberId: memberId,
      OpenId: openId,
      UnionId: unionId,
      Channel: channel
    }).then(response => {
      wx.setStorageSync(STORAGE_KEY.afterRemove, 1)
      if (!response || response.status !== 200) {
        return
      }
      if (!response.data || response.data.Code !== 10000) {

        wx.showToast({
          title: response.data.Message || '删除失败',
          icon: 'none',
          duration: 1000,
        })
        return
      }
      asyncToast({
        title: '删除成功',
        icon: 'success',
        duration: 1000,
      }).then(() => {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('createPassengerChannel', { data: {} });
        that.resetForm();
        wx.navigateBack()
      })

    }).catch(() => {
      wx.showToast({
        title: '删除失败',
        icon: 'none',
        duration: 2000
      })
    })
  },


  // 证件识别
  certIdentification: function () {
    const that = this
    const { editId } = this.data.query
    let editForm = that.data.editForm
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      count: 1,
      success: data => {

        getScanCertificateApi({
          filePath: data.tempFilePaths[0],
          name: 'file'
        }).then((res) => {
          if (res.statusCode === 200) {
              const result = JSON.parse(res.data)
              const resData = result.data
              if (!result.isSuccess || !resData || !resData.idnum) {
                  that.setData({
                      isOpenVerifyFail: true
                  })

                  setEvent('订单填写页', 'DD33', '^识别失败^')
                  return;
              }

              var opt = {}
              if (editId) {
                  opt = form
              }
              opt.linkerName = resData.name;
              // opt.englishXin = resData.englishXin;
              // opt.englishMing = resData.englishMing;
              opt.firstCertType = editForm.firstCertType;
              opt.firstCertNo = resData.idnum;
              opt.sex = resData.gender === '女'? 0: 1;

              const birthday = resData.birthday
              if(birthday) {
                opt.birthday = `${birthday.year}-${birthday.month}-${birthday.day}`;
              }
              
              setEvent('订单填写页', 'DD33', '^识别成功^')
           
              that.setData({
                isOpenVerify: true,
                formTemp: opt
              })
          }
        }).catch(err => {
          // 
          console.log(err)
        })
      }
    })
  },

  oncertIdentityTips: function () {
    const isOpenScanDesc = this.data.isOpenScanDesc
    this.setData({
      isOpenScanDesc: !isOpenScanDesc
    })
  },

  handleCloseVerifyFail: function () {
    this.setData({
      isOpenVerifyFail: false
    })
  },
  handleCancelVerifyFail: function () {
    this.setData({
      isOpenVerifyFail: false
    })
  },
  handleConfirmVerifyFail: function () {
    this.setData({
      isOpenVerifyFail: false
    })
  },

  cancelFormTemp: function () {
    this.setData({
      isOpenVerify: false
    })
  },
  setFormTempToForm: function () {
    const formTemp = this.data.formTemp
    const editForm = this.data.editForm
    const settings = this.data.settings
    const { supplierId } = this.data.query
    
    const _formTemp = setEditForm(formTemp, settings, true, editForm)
    const formItems = buildForm(false, settings, supplierId, _formTemp)
    const isFormValid = this._validForm(formItems)

    this.setData({
      isFormValid,
      formItems,
      editForm: _formTemp,
      isOpenVerify: false
    })
  },


  onExamHandler: function (e) {
    const item = e.currentTarget.dataset.item

    this.setData({
      certExamObj: {
        title: item.remindTitle,
        img: item.remindImg
      },
      isOpenCertExam: true
    })
  },

  closeCertExam: function () {
    this.setData({
      isOpenCertExam: false
    })
  },
  confirmCertExam: function () {
    this.setData({
      isOpenCertExam: false
    })
  },

  onCancelValidForm: function () {
    this.setData({
      validDialog: {
        show: false,
        list: [],
        success: () => { }
      }
    })
  },
  onConfirmValidForm: function (e) {
    const validDialog = this.data.validDialog

    validDialog.success(e).then(() => {
      this.onCancelValidForm()
    })
  },
})